package com.example.cwproject.service.serviceImpl;

import com.example.cwproject.entity.User;
import com.example.cwproject.exception.ServiceException;
import com.example.cwproject.mapper.EmailMapper;
import com.example.cwproject.mapper.UserMapper;
import com.example.cwproject.service.EmailService;
import com.example.cwproject.service.UserService;
import com.example.cwproject.utils.CharUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EmailMapper emailMapper;

    //更新用户个人信息
    @Override
    public void updateUser(User user) {
        userMapper.update(user);
    }

    //根据邮箱返回用户信息
    @Override
    public User findByEmail(String email){
        return userMapper.selectUserByEmail(email);
    }

    //验证用户是否合法
    @Override
    public String login(User user) {
        //根据用户名查询数据库的用户信息
        User dbUser = userMapper.selectReturnUser(user.getEmail());
        String password = userMapper.selectReturnPassword(user.getEmail());
        if(dbUser == null){
            //抛出一个自定义异常
            throw new ServiceException("账号不存在");
        }
        if(!user.getPassword().equals(password)){
            throw new ServiceException("用户密码错误,正确的密码为："+ password+"，您的密码为："+user.getPassword());
        }
        return "登入成功";
    }

    @Override
    public User register(User user){

        //验证邮箱
        String verifyCode = emailMapper.selectByEmail(user.getEmail());
        if(verifyCode == null){
            throw new ServiceException("验证码不存在");
        }else if(verifyCode.equals(user.getCode())){
            userMapper.insert(user);
        }else {
            throw new ServiceException("验证码错误,您输入的验证码为："+user.getCode());
        }

        return user;
    }

    @Override
    public void modifyPassword(String newPassword, String email) {
        userMapper.modifyPassword(newPassword, email);
    }

    @Override
    public void uploadAvatar(String fileName, String email) {
        userMapper.uploadAvatar(fileName,email);
    }

}
